/**************************************************************************(C)*
 *
 *  This file is part of the GreenHills project
 *  Copyright (C) 2009  Tieto Corporation
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  Not for commmercial use. Only with Tieto permission.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************(C)*/

#include "../message.h"
#include <memory.h>

using namespace greenhills::io;

CMessage::CMessage(const char *pData,
                   unsigned int pLength,
                   bool pAddLengthToData)
        : mData(0)
{
    setData(pData, pLength, pAddLengthToData);
}

CMessage::~CMessage()
{
    clear();
}

const char* CMessage::getData()
{
    return mData;
}

const char* CMessage::getRemainingData()
{
    return (mData + mPosition);
}

unsigned int CMessage::getLength()
{
    return mLength;
}

unsigned int CMessage::getRemainingLength()
{
    return (mLength - mPosition);
}

unsigned int CMessage::getPosition()
{
    return mPosition;
}

void CMessage::increasePosition(unsigned int pStep)
{
    mPosition += pStep;
}

void CMessage::setData(const char *pData,
                       unsigned int pLength,
                       bool pAddLengthToData)
{
    clear();

    if (pData == 0) {
        return;
    }

    if (pAddLengthToData) {
        mData = new char[pLength + sizeof(pLength)];
        memcpy(mData, &pLength, sizeof(pLength));
        memcpy(mData + sizeof(pLength), pData, pLength);
        mLength = pLength + sizeof(pLength);
    } else {
        mData = new char[pLength];
        memcpy(mData, pData, pLength);
        mLength = pLength;
    }
}

void CMessage::clear()
{
    if (mData != 0) {
        delete[] mData;
        mData = 0;
    }

    mLength = 0;
    mPosition = 0;
}
